package com.git_taoxian.test4;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class Test {
    public static void main(String[] args) {
//        创建一个Person类对象
        Class clz = Person.class;
        try {
//        获取有参构造方法的对象
            Constructor constructor = clz.getDeclaredConstructor(String.class, int.class);
            Person rs = (Person) constructor.newInstance("张三",23);
            System.out.println(rs);
//        获取成员变量对象
            Field age = clz.getDeclaredField("age");
//        强势反射
            age.setAccessible(true);
//        对成员变量进行初始化
            Person person = (Person) clz.getDeclaredConstructor().newInstance();
            age.set(person,18);
//        打印输出
            System.out.println(age.get(person));
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
